import {
  WebGLRenderer,
  PerspectiveCamera,
  Scene,
  DirectionalLight,
  AmbientLight,
  sRGBEncoding,
} from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { EventDispatcher } from "three";
export default class InitScene extends EventDispatcher {
  renderer!: WebGLRenderer;
  scene: Scene;
  camera: PerspectiveCamera;
  canvas!: HTMLCanvasElement;
  controls!: OrbitControls;
  cameraPlace: { [key: string]: number } = { x: -20, y: 20, z: 100 };
  constructor() {
    super();
    this.scene = new Scene();
    this.camera = new PerspectiveCamera(
      45,
      window.innerWidth / window.innerHeight,
      0.01,
      10000
    );

    this.camera.position.set(
      this.cameraPlace.x,
      this.cameraPlace.y,
      this.cameraPlace.z
    );
    const light = new DirectionalLight(0xcccccc, 1);
    light.position.set(20, 20, 20);
    this.scene.add(light);
    const ambientLight = new AmbientLight(0xffffff); // soft white light
    this.scene.add(ambientLight);
  }
  init(canvas: HTMLCanvasElement) {
    this.renderer = new WebGLRenderer({
      canvas,
      antialias: true,
      logarithmicDepthBuffer:true
    });
    this.renderer.outputEncoding = sRGBEncoding;
    this.canvas = canvas;
    // this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    // this.controls.update();
    // this.controls.enableZoom = false;
    this.resize();
    this.animate();
    return this;
  }
  changeChontrols(domElement: HTMLElement) {
    this.controls = new OrbitControls(this.camera, domElement);
  }
  animate() {
    this.renderer.render(this.scene, this.camera);
    // this.controls.update();
    requestAnimationFrame(() => {
      this.animate();
    });
    this.dispatchEvent({
      type: "animate",
    });
  }
  resize() {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize(window.innerWidth, window.innerHeight);
  }
  resetScene() {
    this.camera.position.set(
      this.cameraPlace.x,
      this.cameraPlace.y,
      this.cameraPlace.z
    ); // 重置相机位置
    this.controls.target.set(0, 0, 0); // 置位控制器目标位置
    this.controls.update(); // 更新控制器
  }
}

export const defaultInitScene = new InitScene();
